package com.yougou.ui.cart;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yougou.R;
import com.yougou.base.BaseFragment;
import com.yougou.data.model.CartItem;
import com.yougou.ui.cart.adapter.CartAdapter;
import com.yougou.ui.product.ProductDetailActivity;
import com.yougou.utils.ToastUtils;

import java.util.Locale;

public class CartFragment extends BaseFragment {
    
    private RecyclerView mRecyclerView;
    private View mEmptyLayout;
    private CheckBox mSelectAllCheckBox;
    private TextView mTotalPriceTextView;
    private TextView mDeleteTextView;
    private Button mCheckoutButton;
    
    private CartAdapter mAdapter;
    private CartViewModel mViewModel;
    
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_cart;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 每次显示时刷新数据
        if (mViewModel != null) {
            mViewModel.loadCartData();
        }
    }
    
    @Override
    protected void initView(View view) {
        mRecyclerView = view.findViewById(R.id.rv_cart);
        mEmptyLayout = view.findViewById(R.id.layout_empty);
        mSelectAllCheckBox = view.findViewById(R.id.cb_select_all);
        mTotalPriceTextView = view.findViewById(R.id.tv_total_price);
        mDeleteTextView = view.findViewById(R.id.tv_delete);
        mCheckoutButton = view.findViewById(R.id.btn_checkout);
        
        // 设置列表
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new CartAdapter();
        mRecyclerView.setAdapter(mAdapter);
        
        // 设置适配器监听
        mAdapter.setOnCartItemChangedListener(new CartAdapter.OnCartItemChangedListener() {
            @Override
            public void onCheckedChanged(CartItem item, boolean checked) {
                mViewModel.updateItemChecked(item, checked);
            }
            
            @Override
            public void onQuantityChanged(CartItem item, int quantity) {
                mViewModel.updateItemQuantity(item, quantity);
            }
            
            @Override
            public void onItemClick(CartItem item) {
                // 跳转到商品详情
                Intent intent = new Intent(requireContext(), ProductDetailActivity.class);
                intent.putExtra(ProductDetailActivity.EXTRA_GOODS_ID, item.getGoods().getGoodsId());
                startActivity(intent);
            }
        });
        
        // 全选功能
        mSelectAllCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            mViewModel.toggleAllChecked(isChecked);
        });
        
        // 删除按钮
        mDeleteTextView.setOnClickListener(v -> mViewModel.deleteCheckedItems());
        
        // 去结算
        mCheckoutButton.setOnClickListener(v -> mViewModel.checkout());
    }
    
    @Override
    protected void initData() {
        mViewModel = new ViewModelProvider(this).get(CartViewModel.class);
        
        // 观察购物车数据
        mViewModel.getCartItems().observe(getViewLifecycleOwner(), items -> {
            if (items != null && !items.isEmpty()) {
                mAdapter.setData(items);
                showCart();
            } else {
                showEmpty();
            }
        });
        
        // 观察总价
        mViewModel.getTotalPrice().observe(getViewLifecycleOwner(), total -> {
            if (total != null) {
                mTotalPriceTextView.setText(String.format(Locale.CHINA, "¥%.2f", total));
            }
        });
        
        // 观察全选状态
        mViewModel.getAllChecked().observe(getViewLifecycleOwner(), checked -> {
            if (checked != null) {
                mSelectAllCheckBox.setOnCheckedChangeListener(null);
                mSelectAllCheckBox.setChecked(checked);
                mSelectAllCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    mViewModel.toggleAllChecked(isChecked);
                });
            }
        });
        
        // 观察消息
        mViewModel.getMessage().observe(getViewLifecycleOwner(), message -> {
            if (message != null) {
                ToastUtils.show(requireContext(), message);
            }
        });
        
        // 观察是否需要登录
        mViewModel.getNeedLogin().observe(getViewLifecycleOwner(), needLogin -> {
            if (needLogin != null && needLogin) {
                // 跳转到登录页面
                Intent intent = new Intent(requireContext(), com.yougou.ui.login.LoginActivity.class);
                startActivity(intent);
            }
        });
        
        // 观察结算数据
        mViewModel.getCheckoutData().observe(getViewLifecycleOwner(), cartItems -> {
            if (cartItems != null && !cartItems.isEmpty()) {
                // 跳转到结算页面
                Intent intent = new Intent(requireContext(), CartCheckoutActivity.class);
                intent.putExtra(CartCheckoutActivity.EXTRA_CART_ITEMS, new java.util.ArrayList<>(cartItems));
                startActivity(intent);
            }
        });
        
        // 加载数据
        mViewModel.loadCartData();
    }
    
    
    private void showEmpty() {
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }
    
    
    private void showCart() {
        mEmptyLayout.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.VISIBLE);
    }
}
